<template>
  <div class="profile-container">
    <div class="profile-card">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>用户信息</span>
            <div>
              <el-button
                v-if="!isEditing"
                type="primary"
                @click="enterEditMode"
                :icon="Edit"
              >
                编辑信息
              </el-button>
              <div v-else>
                <el-button type="success" @click="saveUserInfo" :icon="Check"
                  >保存</el-button
                >
                <el-button @click="cancelEdit" :icon="Close">取消</el-button>
              </div>
            </div>
          </div>
        </template>

        <el-row :gutter="20">
          <!-- 用户头像 -->
          <el-col :span="24" class="avatar-section">
            <el-avatar :src="userInfo.icon" :size="100" />
            <div class="username">{{ userInfo.username }}</div>
          </el-col>
        </el-row>

        <el-tabs v-model="activeTab" class="profile-tabs">
          <el-tab-pane label="基本信息" name="basic">
            <el-form
              :model="userInfo"
              label-width="100px"
              :disabled="!isEditing"
              class="profile-form"
            >
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="用户ID">
                    <el-input v-model="userInfo.userid" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="用户名">
                    <el-input v-model="userInfo.username" disabled />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="手机号">
                    <el-input v-model="userInfo.phone" :disabled="!isEditing" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="邮箱">
                    <el-input v-model="userInfo.email" :disabled="!isEditing" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="用户类型">
                    <el-input :value="getUserType(userInfo.utypeid)" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="账户状态">
                    <el-tag
                      :type="userInfo.isdeleted === 0 ? 'success' : 'danger'"
                    >
                      {{ userInfo.isdeleted === 0 ? "正常" : "已封禁" }}
                    </el-tag>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-tab-pane>

          <el-tab-pane label="详细信息" name="detail">
            <el-form
              v-if="userInfo.tuserinfo"
              :model="userInfo.tuserinfo"
              label-width="100px"
              :disabled="!isEditing"
              class="profile-form"
            >
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="真实姓名">
                    <el-input
                      v-model="userInfo.tuserinfo.realName"
                      :disabled="!isEditing"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="身份证号">
                    <el-input
                      v-model="userInfo.tuserinfo.idCard"
                      :disabled="!isEditing"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="驾照等级">
                    <el-select
                      v-model="userInfo.tuserinfo.drivingLicenseLevel"
                      :disabled="!isEditing"
                      style="width: 100%"
                    >
                      <el-option label="C1" value="C1" />
                      <el-option label="C2" value="C2" />
                      <el-option label="B1" value="B1" />
                      <el-option label="B2" value="B2" />
                      <el-option label="A1" value="A1" />
                      <el-option label="A2" value="A2" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="联系电话">
                    <el-input
                      v-model="userInfo.tuserinfo.phone"
                      :disabled="!isEditing"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="邮箱">
                    <el-input
                      v-model="userInfo.tuserinfo.email"
                      :disabled="!isEditing"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="账户状态">
                    <el-tag
                      :type="
                        userInfo.tuserinfo.status === 1 ? 'success' : 'danger'
                      "
                    >
                      {{ userInfo.tuserinfo.status === 1 ? "正常" : "禁用" }}
                    </el-tag>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="地址">
                <el-input
                  v-model="userInfo.tuserinfo.address"
                  type="textarea"
                  :disabled="!isEditing"
                />
              </el-form-item>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="注册时间">
                    <el-date-picker
                      v-model="userInfo.tuserinfo.createTime"
                      type="datetime"
                      disabled
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="更新时间">
                    <el-date-picker
                      v-model="userInfo.tuserinfo.updateTime"
                      type="datetime"
                      disabled
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <div v-if="extraInfo">
                <el-divider content-position="left">扩展信息</el-divider>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="工作单位">
                      <el-input
                        v-model="extraInfo.work_unit"
                        :disabled="!isEditing"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="紧急联系人">
                      <el-input
                        v-model="extraInfo.emergency_contact"
                        :disabled="!isEditing"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import { Edit, Check, Close } from "@element-plus/icons-vue";
import api from "@/util/service";
import { useLoginStore } from "@/stores/userStores";

const userStore = useLoginStore();

// 用户信息数据
const userInfo = ref({
  userid: null,
  username: "",
  utypeid: null,
  email: "",
  phone: "",
  password: "",
  info: "",
  icon: "",
  isdeleted: 0,
  lid: null,
  menus: null,
  tuserinfo: {
    uinfoId: null,
    realName: "",
    idCard: "",
    drivingLicenseLevel: "",
    phone: "",
    email: "",
    address: "",
    createTime: "",
    updateTime: "",
    status: 1,
    avatarUrl: "",
    password: "",
    salt: "",
    extraInfo: "",
  },
});

// 编辑模式控制
const isEditing = ref(false);
const activeTab = ref("detail");
const originalUserInfo = ref({});

// 路由信息
const route = useRoute();

// 获取扩展信息
const extraInfo = computed({
  get: () => {
    if (userInfo.value.tuserinfo && userInfo.value.tuserinfo.extraInfo) {
      try {
        return typeof userInfo.value.tuserinfo.extraInfo === "string"
          ? JSON.parse(userInfo.value.tuserinfo.extraInfo)
          : userInfo.value.tuserinfo.extraInfo;
      } catch (e) {
        console.error("解析 extraInfo 失败:", e);
        return {};
      }
    }
    return {};
  },
  set: (value) => {
    if (userInfo.value.tuserinfo) {
      userInfo.value.tuserinfo.extraInfo = JSON.stringify(value);
    }
  },
});

// 获取用户类型名称
const getUserType = (typeId) => {
  const types = {
    0: "超级管理员",
    1: "管理员",
    2: "普通用户",
  };
  return types[typeId] || "未知";
};

// 进入编辑模式
const enterEditMode = () => {
  isEditing.value = true;
  // 保存原始数据用于取消编辑时恢复
  originalUserInfo.value = JSON.parse(JSON.stringify(userInfo.value));
};

// 取消编辑
const cancelEdit = () => {
  isEditing.value = false;
  // 恢复原始数据
  userInfo.value = JSON.parse(JSON.stringify(originalUserInfo.value));
};

// 保存用户信息
const saveUserInfo = async () => {
  try {
    // 准备要提交的数据
    const submitData = {
      ...userInfo.value.tuserinfo,
      extraInfo: JSON.stringify(extraInfo.value),
    };

    const response = await api.post("/tuser/updateUser", submitData);

    if (response.code === 200) {
      ElMessage.success("用户信息更新成功");
      isEditing.value = false;
      // 重新获取用户信息以确保数据同步
      fetchUserInfo(userInfo.value.userid);
    } else {
      ElMessage.error(response.message || "更新失败");
    }
  } catch (error) {
    console.error("保存用户信息失败:", error);
    ElMessage.error("保存用户信息失败");
  }
};

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const params = { userid: userStore.getId };
    const response = await api.post("/tuser/selectUser", params);

    if (response.code === 200) {
      userInfo.value = response.data;

      // 确保tuserinfo存在
      if (!userInfo.value.tuserinfo) {
        userInfo.value.tuserinfo = {
          realName: "",
          idCard: "",
          drivingLicenseLevel: "",
          phone: "",
          email: "",
          address: "",
          createTime: "",
          updateTime: "",
          status: 1,
          avatarUrl: "",
          password: "",
          salt: "",
          extraInfo: "{}",
        };
      }
    }
  } catch (error) {
    console.error("获取用户信息失败:", error);
    ElMessage.error("获取用户信息失败");
  }
};

// 组件挂载时获取用户信息
onMounted(() => {
  // 从路由参数获取用户ID，如果没有则使用默认值2
  const userId = route.params.userId || 2;
  fetchUserInfo(userId);
});
</script>

<style scoped>
.profile-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: calc(100vh - 100px);
  padding: 20px;
  background-color: #f5f7fa;
}

.profile-card {
  width: 100%;
  max-width: 1000px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.avatar-section {
  text-align: center;
  margin-bottom: 20px;
}

.username {
  margin-top: 15px;
  font-size: 20px;
  font-weight: bold;
}

.profile-tabs {
  margin-top: 20px;
}

.profile-form {
  margin-top: 20px;
}

.profile-form :deep(.el-form-item) {
  margin-bottom: 20px;
}

@media (max-width: 768px) {
  .profile-card {
    margin: 10px;
  }

  :deep(.el-col) {
    width: 100%;
  }
}
</style>
